package com.hmall.gateway.filters;

import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        // 1. 判断请求是否需要做登录拦截（isExclude为自定义方法）
        if(isExclude(request.getPath().toString())) {
            return chain.filter(exchange); // 不需要，则放行
        }

        // 2. 获的请求头中的token
        String token = request.getHeaders().getFirst("authorization");

        // 3. 解析并校验token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token); // 不怕抛异常则解析成功
        } catch (Exception e) {
            // token验证失败，不放行，返回401
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        //TODO 4. 传递用户信息到微服务
        String userInfo = userId.toString();
        ServerWebExchange exchanged = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();

        // 5. 放行, 并传入修改后的exchange
        return chain.filter(exchanged);
    }

    // 判断请求是否被排除
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private boolean isExclude(String requestPath) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(excludePath, requestPath)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
